/**
 * 用户信息
 */
import { getToken, setToken, removeToken } from "@/utils/auth"
import { loginAPI, userInfoAPI } from "@/api/user.js"
import { constantRoutes } from "@/router/index.js"  // 静态路由
import { resetRouter } from "@/router/index.js"

const state = {
  token: getToken(),   // token
  userInfo: {},    // 用户信息
  routes: constantRoutes  // 用户可访问路由
}

const mutations = {
  // 设置token
  setStateToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 删除token
  delToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 设置用户可访问路由
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  // 登录
  async loginActions(content, data) {
    const token = await loginAPI(data)
    content.commit("setStateToken", token)
  },
  // 获取用户信息
  async userInfoActions(content) {
    const res = await userInfoAPI()
    content.commit('setUserInfo', res)
    return res
  },
  // 退出登录 删除用户信息
  loginOutActions(content) {
    content.commit('delToken') // 删除token
    content.commit('setUserInfo', {}) // 删除用户信息
    resetRouter() // 清除路由信息
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

